home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 14312 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  80 lines

  1. Path: news.sprintlink.net!datalytics!usenet
  2. From: Rob Stewart <stew@datalytics.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Derivation and calling virtual functions
  5. Date: Fri, 29 Mar 1996 14:09:59 -0500
  6. Organization: Datalytics, Inc
  7. Message-ID: <315C3587.293F@datalytics.com>
  8. References: <graphix.828032689@spiff.cc.iastate.edu>
  9. NNTP-Posting-Host: 204.62.224.71
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (WinNT; I)
  14.  
  15. Kent A Vander Velden wrote:
  16. >   Say we have the following:
  17. > class Base {
  18. > public:
  19. >   virtual void func() { // some stuff }
  20. >   virtual void write() { func(); };
  21. > };
  22. > class Derived : public Base {
  23. > public:
  24. >   void func() { // some stuff }
  25. >   write(); { Base::func(); }
  26. > };
  27. > Derived inst;
  28. >   Now, when I call inst.write() it in turn calls Bass::write() which in
  29. > turn calls Base::func().  Is there a way to instead have it call
  30. > Derived::func() if the instance is of type Derived?  I hoped the
  31. > virtual keyword would help in this case.
  32.  
  33. inst.write() calls Derived::write().  That function is written 
  34. to call Base::func().
  35.  
  36. To do what you want, write your classes like this:
  37.  
  38. class B
  39. {
  40.    public:
  41.       virtual
  42.       void     func(void);
  43.       void     write(void) { func(); };
  44. };
  45. class D : public B
  46. {
  47.    public:
  48.       virtual
  49.       void     func(void);
  50. };
  51.  
  52. Then, write code to use it like this:
  53.  
  54. D itD;
  55. B& it = itD;
  56. it.write();
  57.  
  58. or like this:
  59.  
  60. B* pIt = new D;
  61. pIt->write();
  62.  
  63. The result is that it.write() and pIt->write() will call 
  64. B::write().  In turn, it will call this->func().  Since func is 
  65. a virtual function and you're calling it though a reference or 
  66. pointer to B, the compiler looks up the address of func from the 
  67. vtable.  Since it (pIt) actually references (points to) a D, 
  68. this->func() will call D::func().
  69.                     QED
  70.  
  71. -- 
  72. Robert Stewart        | My opinions are usually my own.
  73. Datalytics, Inc.    | stew@datalytics.com
  74.